﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using WCS.Utils;
using WCS.Helpers;
using WCS.Entity;
using WcsTask;
using SqlSugar;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using WCS.Controls.RunLog;
using System.IO;

namespace WCS.Controls.系统查询
{
    public partial class AddTask : UIPage
    {
        public AddTask()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 数据库连接对象
        /// </summary>
        static SqlSugarDapper SqlSugarDapper = SqlSugarDapper.GetDbContext();
        public static string path = AppDomain.CurrentDomain.BaseDirectory + "logs";

        //死锁
        public static object loglock = new object();
        Dictionary<string, string> dicIn = null;

        public static string GenerateRandomCode()
        {
            var result = new StringBuilder();
            for (var i = 0; i < 6; i++)
            {
                var r = new Random(Guid.NewGuid().GetHashCode());
                result.Append(r.Next(0, 10));
            }
            return result.ToString();
        }

        private void AddTask_Load(object sender, EventArgs e)
        {
            dicIn = new Dictionary<string, string>
            {
                { "1号入库口", "A002" },
                { "2号入库口", "A006" },
            };

            uiComboBox2.DataSource = new BindingSource(dicIn, null);
            uiComboBox2.DisplayMember = "key";
            uiComboBox2.ValueMember = "value";

            uiComboBox2.Text = "1号入库口";

            var tem = SqlSugarDapper.DB.Queryable<WcsDevPlc>()
                              .Where(w => w.PLC_Name == "铸造区")
                              .First();

            this.uiTextBox3.Watermark = tem.ATTRIBUTE3;
            this.uiTextBox4.Watermark = tem.ATTRIBUTE4;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ProcessingTaskMain._processingTaskMain._ControlA002 = "0";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ProcessingTaskMain._processingTaskMain._ControlA006 = "0";
        }

        private void uiComboBox1_DropDown(object sender, EventArgs e)
        {
            //更新数据
            var id = SqlSugarDapper.DB.Queryable<WcsTaskAGV>().ToList().GroupBy(g => g.AGVTaskID).ToList();
            uiComboBox1.Items.Clear();
            foreach (var item in id)
            {
                uiComboBox1.Items.Add(item.Key);
            }
        }

        /// <summary>
        /// 删除AGV任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton3_Click(object sender, EventArgs e)
        {
            //获取任务号 删除任务
            var taskCode = uiComboBox1.Text;

            var mainTask = SqlSugarDapper.DB.Queryable<WcsTaskAGV>().Where(w => w.AGVTaskID == Convert.ToInt32(taskCode)).First();


            DialogResult res = MessageBox.Show("确定要删除AGV任务吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Deleteable<WcsTaskMain>().Where(w => w.Task_Code == mainTask.Task_Code).ExecuteCommand();
                SqlSugarDapper.DB.Deleteable<WcsTaskAGV>().Where(w => w.AGVTaskID == Convert.ToInt32(taskCode)).ExecuteCommand();

                MessageBox.Show("删除任务成功");
                WriteLog("Info", $"删除AGV任务{taskCode}");
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 重新下发出库任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("确定要重新下发任务吗？", "下发提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Updateable<WcsTaskConveyor>()
                .SetColumns(w => w.Task_State == (int)Task_State.等待执行)
                .Where(w => (w.Current_Station == "9001" || w.Current_Station == "9002") && w.Task_State == (int)Task_State.执行中 && w.Task_Type == "out")
                .ExecuteCommand();

                MessageBox.Show("重新下发输送线任务成功");

            }
        }

        /// <summary>
        /// 删除叫料任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton2_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("确定要删除叫料任务吗？", "下发提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Deleteable<WCS.Entity.CallMaterial>()
                .Where(w => !w.CallStation.IsNullOrEmpty()).ExecuteCommand();

                MessageBox.Show("删除叫料信息成功");
                WriteLog("Info", $"删除叫料任务");

            }
        }

        private void uiCBoxinfo_DropDown(object sender, EventArgs e)
        {
            var id = SqlSugarDapper.DB.Queryable<Warehouse>().ToList().GroupBy(g => g.ID).ToList();
            uiCBoxinfo.Items.Clear();
            foreach (var item in id)
            {
                uiCBoxinfo.Items.Add(item.Key);
            }
        }

        private void uiButtonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (uiTextBox2.Text.Length != 3)
                {
                    MessageBox.Show("条码只需要输入后三位");
                    return;
                }
                var lastCode = SqlSugarDapper.DB.Queryable<WarehouseInfo>()
                                        .Where(w => w.ID == uiCBoxinfo.Text && w.state == 55)
                                        .OrderBy(o => o.index, OrderByType.Asc).ToList().Last();

                var material = SqlSugarDapper.DB.Queryable<Warehouse>()
                    .Where(w => w.ID == uiCBoxinfo.Text).First().MaterialType;

                var code = SqlSugarDapper.DB.Queryable<Entity.PalletToMaterial>()
                       .Where(w => w.MaterialType == material)
                       .First().PalletCode;

                var codes = "810373" + code + uiTextBox2.Text;

                if (lastCode == null)
                {
                    DialogResult ress = MessageBox.Show($"确定要添加{uiCBoxinfo.Text}的库存吗？", "添加提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                    if (ress == DialogResult.OK)
                    {
                        SqlSugarDapper.DB.Insertable(new WarehouseInfo
                        {
                            ID = uiCBoxinfo.Text,
                            index = 1,
                            barCode = codes,
                            state = (int)StationState.在库,
                            CreateTime = DateTime.Now,
                        }).ExecuteCommand();
                    }
                    MessageBox.Show($"添加库存楼层:【{uiCBoxinfo.Text}】条码:【{code}】信息成功");
                    WriteLog("Info", $"添加库存楼层:【{uiCBoxinfo.Text}】条码:【{code}】信息成功");

                    uiTextBox2.Text = "";
                }
                else
                {
                    DialogResult res = MessageBox.Show($"确定要添加{lastCode.ID}的库存吗？", "添加提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (res == DialogResult.OK)
                    {
                        var barcode = (Convert.ToInt64(lastCode.barCode) + 1).ToString();
                        SqlSugarDapper.DB.Insertable(new WarehouseInfo
                        {
                            ID = uiCBoxinfo.Text,
                            index = lastCode.index + 1,
                            barCode = codes,
                            state = (int)StationState.在库,
                            CreateTime = lastCode.CreateTime,
                        }).ExecuteCommand();

                        MessageBox.Show($"添加库存楼层:【{lastCode.ID}】条码:【{barcode}】信息成功");
                        WriteLog("Info", $"添加库存楼层:【{lastCode.ID}】条码:【{barcode}】信息成功");

                        uiTextBox2.Text = "";

                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

        }

        private void uiButtonRemove_Click(object sender, EventArgs e)
        {
            try
            {
                var lastCode = SqlSugarDapper.DB.Queryable<WarehouseInfo>()
                                .Where(w => w.ID == uiCBoxinfo.Text && w.state == 55)
                                .OrderBy(o => o.index, OrderByType.Asc).ToList().Last();

                if (lastCode == null)
                {
                    MessageBox.Show($"楼层:【{uiCBoxinfo.Text}】没有库存");

                }
                else
                {
                    DialogResult res = MessageBox.Show($"确定要删除{lastCode.ID}的库存吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (res == DialogResult.OK)
                    {
                        SqlSugarDapper.DB.Deleteable<WarehouseInfo>()
                                         .Where(w => w.ID == lastCode.ID && w.index == lastCode.index && w.barCode == lastCode.barCode && w.state == (int)StationState.在库)
                                         .ExecuteCommand();

                        MessageBox.Show($"删除楼层:【{lastCode.ID}库存成功】");
                        WriteLog("Info", $"删除楼层:【{lastCode.ID}库存成功】");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show($"确定初始化入库站台吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Deleteable<LocationInfo>()
                .Where(w => w.StationLocation.Contains("10"))
                .ExecuteCommand();

                for (int i = 1; i < 9; i++)
                {
                    var strMaterial = SqlSugarDapper.DB.Queryable<WcsDevStation>()
                                                .Where(w => w.Station_Plc_No == $"100{i}")
                                                .First();

                    SqlSugarDapper.DB.Insertable(new LocationInfo
                    {
                        MaterialInfo = strMaterial.ProductionMaterials,
                        StationLocation = strMaterial.Station_Plc_No,
                        state = (int)StationState.在库
                    }).ExecuteCommand();
                }
                MessageBox.Show($"初始化入库站台完成");
                WriteLog("Info", $"初始化入库站台完成");

            }
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            ProcessingTaskMain._processingTaskMain._ControlA002 = "0";
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {
            ProcessingTaskMain._processingTaskMain._ControlA006 = "0";
        }

        /// <summary>
        /// 手动输入条码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton7_Click(object sender, EventArgs e)
        {
            if (uiComboBox3.Text == "" || uiTextBox1.Text == "")
            {
                MessageBox.Show($"不能为空！！！");
                return;
            }
            if (uiTextBox1.Text.Length != 3)
            {
                MessageBox.Show($"条码为三位数");
                return;
            }
            //var code = "";
            //switch (uiComboBox3.Text)
            //{
            //    case "X03后副车架砂芯":
            //        code = "81037320063630";
            //        break;
            //    case "NPC后副车架砂芯":
            //        code = "81037320063102";
            //        break;
            //    case "XC40后副车架砂芯":
            //        code = "81037320063111";
            //        break;
            //    default:
            //        break;
            //}
            var code = SqlSugarDapper.DB.Queryable<Entity.PalletToMaterial>()
                    .Where(w => w.MaterialType == uiComboBox3.Text)
                    .First().PalletCode;

            var codes = "810373" + code + uiTextBox1.Text;
            var inStation = dicIn.GetValue(uiComboBox2.Text);

            DialogResult res = MessageBox.Show($"确定要重新写入{codes}吗？", "写入提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Updateable<WcsReadTrayCode>()
                 .SetColumns(w => w.TrayBar_Code == codes)
                 .Where(w => w.Station_Plc_No == inStation)
                 .ExecuteCommand();

                MessageBox.Show($"重新写入条码{codes}到{uiComboBox2.Text}成功");
                WriteLog("Info", $"重新写入条码{codes}到{uiComboBox2.Text}成功");

                uiTextBox1.Text = "";
                uiComboBox3.Text = "";
            }
        }

        /// <summary>
        /// 砂芯类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiComboBox3_DropDown(object sender, EventArgs e)
        {
            var id = SqlSugarDapper.DB.Queryable<Entity.PalletToMaterial>().ToList()
                .Where(w => !w.MaterialType.Contains("物料"))
                .GroupBy(g => g.MaterialType).ToList();
            uiComboBox3.Items.Clear();
            foreach (var item in id)
            {
                uiComboBox3.Items.Add(item.Key);
            }
        }

        private void uiGroupBox7_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 修改温度临界值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton8_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(uiTextBox3.Text) > 60 || Convert.ToInt16(uiTextBox3.Text) < 15)
            {
                MessageBox.Show($"温度值输入有误");
                return;
            }
            SqlSugarDapper.DB.Updateable<WcsDevPlc>()
                            .SetColumns(a => a.ATTRIBUTE3 == uiTextBox3.Text)
                            .Where(w => w.PLC_Name == "铸造区").ExecuteCommand();

            MessageBox.Show($"温度临界值修改成功");
            WriteLog("Info", $"温度临界值修改成功,{uiTextBox3.Text}");

            uiTextBox3.Watermark = uiTextBox3.Text;

        }

        /// <summary>
        /// 修改湿度临界值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton9_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(uiTextBox4.Text) > 50 || Convert.ToInt16(uiTextBox4.Text) < 10)
            {
                MessageBox.Show($"湿度值输入有误");
                return;
            }

            SqlSugarDapper.DB.Updateable<WcsDevPlc>()
                            .SetColumns(a => a.ATTRIBUTE4 == uiTextBox4.Text)
                            .Where(w => w.PLC_Name == "铸造区").ExecuteCommand();
            MessageBox.Show($"湿度临界值修改成功");
            WriteLog("Info", $"湿度临界值修改成功,{uiTextBox4.Text}");

            uiTextBox4.Watermark = uiTextBox4.Text;

        }

        /// <summary>
        /// 输送线任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiComboBox4_DropDown(object sender, EventArgs e)
        {
            var id = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().ToList().GroupBy(g => g.Sub_TaskCode).ToList();
            uiComboBox4.Items.Clear();
            foreach (var item in id)
            {
                uiComboBox4.Items.Add(item.Key);
            }
        }

        private void uiButton10_Click(object sender, EventArgs e)
        {
            //获取任务号 删除任务
            var taskCode = uiComboBox4.Text;

            var mainTask = SqlSugarDapper.DB.Queryable<WcsTaskConveyor>().Where(w => w.Sub_TaskCode == taskCode).First();
            DialogResult res = MessageBox.Show("确定要删除输送线任务吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Deleteable<WcsTaskConveyor>().Where(w => w.Sub_TaskCode == taskCode).ExecuteCommand();
                if (mainTask.Task_Type == "out")
                {
                    SqlSugarDapper.DB.Deleteable<WarehouseInfo>().Where(w => w.barCode == mainTask.TrayBar_Code && w.ID == mainTask.Start_Station + "-" + mainTask.WMSBinCode).ExecuteCommand();
                }
                else
                {
                    SqlSugarDapper.DB.Deleteable<WarehouseInfo>().Where(w => w.barCode == mainTask.TrayBar_Code && w.ID == mainTask.End_Station + "-" + mainTask.WMSBinCode).ExecuteCommand();
                }

                MessageBox.Show("删除任务成功");
                WriteLog("Info", $"删除任务成功,{taskCode}");

            }
            else
            {
                return;
            }
        }

        private void uiButton11_Click(object sender, EventArgs e)
        {
            try
            {
                if (uiCBoxinfo.Text == "")
                {
                    MessageBox.Show($"请选择楼层");
                    return;
                }
                var lastCode = SqlSugarDapper.DB.Queryable<WarehouseInfo>()
                                .Where(w => w.ID == uiCBoxinfo.Text && w.state == 75)
                                .OrderBy(o => o.index, OrderByType.Asc).ToList().First();

                if (lastCode == null)
                {
                    MessageBox.Show($"楼层:【{uiCBoxinfo.Text}】没有可删除库存");
                    return;

                }
                else
                {
                    DialogResult res = MessageBox.Show($"确定要删除{lastCode.ID}的库存吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (res == DialogResult.OK)
                    {
                        SqlSugarDapper.DB.Deleteable<WarehouseInfo>()
                                         .Where(w => w.ID == lastCode.ID && w.index == lastCode.index && w.barCode == lastCode.barCode && w.state == (int)StationState.出库占用)
                                         .ExecuteCommand();

                        MessageBox.Show($"删除楼层:【{lastCode.ID}库存成功】");
                        WriteLog("Info", $"删除楼层:【{lastCode.ID}库存成功】");

                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        protected static void WriteLog(string type, string content)
        {
            lock (loglock)
            {
                if (!Directory.Exists(path + "/" + type))//如果日志目录不存在就创建
                {
                    Directory.CreateDirectory(path + "/" + type);
                }

                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");//获取当前系统时间
                string filename = path + "/" + type + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名

                //创建或打开日志文件，向日志文件末尾追加记录
                StreamWriter mySw = File.AppendText(filename);

                //向日志文件写入内容
                string write_content = time + ": " + content;
                mySw.WriteLine(write_content);

                //关闭日志文件
                mySw.Close();
            }
        }

        /// <summary>
        /// 删除入库任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton12_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("确定要删除输送线任务吗？", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                SqlSugarDapper.DB.Deleteable<WarehouseInfo>().Where(w => w.index == 999999999).ExecuteCommand();
                SqlSugarDapper.DB.Deleteable<WcsTaskConveyor>().Where(w => w.Task_Type == "in" && w.Start_Station.Contains("A00")&&w.TrayBar_Code!="").ExecuteCommand();
                SqlSugarDapper.DB.Deleteable<WcsTaskMain>().Where(w => w.Task_Type == "in" && w.Start_Station.Contains("A00") && w.TrayBar_Code != "").ExecuteCommand();

                MessageBox.Show("删除任务成功");
                WriteLog("Info", $"删除所有入库任务完成");

            }
            else
            {
                return;
            }
        }
    }
}
